package com.appkudos.view;

import com.appkudos.controller.GroupController;
import com.appkudos.controller.RecController;
import com.appkudos.controller.UserController;
import com.appkudos.model.Group;
import com.appkudos.model.User;
import com.appkudos.model.App;
import com.appkudos.view.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class GroupAppsActivity extends Activity implements ViewBinder, OnClickListener{
    // list view for displaying the installed apps
	private ListView lv;
	private ArrayList list;
	private PackageManager pm;
	private TextView title_tv;
	private Activity PARENTACTIVITY;
	UserController uc;
	GroupController gc;
	User user;
	App app;
	Group group;
	User friend;
	
	// widgets from app
	String appName;
	String appDesc;
	String appId;
	//User friend;
	ArrayList<Group> groups;
	Button recBtn;
	
	// widgets for write review
	Bundle extras;
	Spinner recToFriendSpinner;
	Spinner recToGroupSpinner;
	TextView appText;
	EditText commentEditText;
	Button postReviewBtn;
	RecController rc =  new RecController();
	String display_option;
	List<Group> user_groups;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PARENTACTIVITY = this;
        // set content view to apps_view xml
        setContentView(R.layout.view_title_list);       
        
        // get data from bundle
        Intent launchIntent = getIntent();
        Bundle extras = launchIntent.getExtras();
        uc = new UserController();
        user = uc.getCurrentUser(extras);
        group = uc.getCurrentGroup(extras);
        
        if(display_option!= null){
	        if(display_option.equals(this.getString(R.string.select_app))){ // display select app
	     	   displaySelectApp();
	        }
	        else if (display_option.compareTo("view_app") == 0){
	        		displayAppActivity(extras.getString("appname"), extras.getString("appdesc"), extras.getString("appid"));
	        	
	        }
        }else{
	        // set the title of the page 
	        title_tv=(TextView)findViewById(R.id.tl_title);
	        title_tv.setText(group.getGroupName()+"'s Apps");
	        
	        // get list view from layout
	        lv=(ListView)findViewById(R.id.tl_list);
			
	        gc = new GroupController();
		    // get associated apps for group
	        list = (ArrayList<App>) gc.getAppsForGroup(group.getGroupID());
	        
	        if(list.size() > 0){
	        	initInstalledApps(list);
	        }else{
	        	Toast.makeText(getApplicationContext(), "no recommendation has been made to the group yet",Toast.LENGTH_LONG).show();
	        }
	        
			// when item is clicked go to app page
		    lv.setOnItemClickListener(new OnItemClickListener() {
		           public void onItemClick(AdapterView<?> parent, View view,
		               int position, long id) {
		             // When clicked, show a toast with the TextView text
		        	 App item = (App) list.get(position);
	//	             Toast.makeText(getApplicationContext(), "position"+position+" name is "+ item.getAppName(),
	//	             Toast.LENGTH_SHORT).show();
	//	                Intent intent = new Intent(PARENTACTIVITY, App.class);
	//	                intent.putExtra("app_name", app.getAppName());
	//	        		startActivity(intent);
		        	 displayAppActivity(item.getAppName(), item.getAppDesc(), item.getAppid());
		             
		           }
		    });
		       
			// set filter on listview
			lv.setTextFilterEnabled(true);
		}
   }
  
    private void initInstalledApps(List<App> list){
    	Map<String, App> itemData;
    	List<Map<String, App>> listData = new ArrayList<Map<String, App>>();
    	
    	// put the apps into a hashmap (used for input by simple adapter)
    	for(int j=0; j<list.size();j++){
    		itemData = new HashMap<String, App>(1);
    		app = (App) list.get(j);
    		itemData.put("group_app_list_linearLayout1", app);
    		listData.add(itemData);
    	}    

    	// bind simple adapter to the list view
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.group_app_list,
                new String[] {
                    "group_app_list_linearLayout1"
                }, new int[] {
                    R.id.group_app_list_linearLayout1
                });
        
        // bind viewBinder to adapter and set adapter to listview
        simpleAdapter.setViewBinder(this);
        lv.setAdapter(simpleAdapter);
    }
        
    
    @Override
    public boolean setViewValue(View view, Object data, String stringRepresetation) {  	
    	// get data for the row
    	App app = (App) data;
        LinearLayout layout = (LinearLayout) view;
        
        // bind information to the textbox and icon
        TextView tv1 = (TextView) layout.findViewById(R.id.group_app_text);
        tv1.setText(app.getAppName());
       
        // display number of times an app has been recommended
//        TextView tv2 = (TextView) layout.findViewById(R.id.group_app_rec_number);
//        tv2.setText(gc.getNRec(app.getAppid(), group.getGroupID()).toString());
        TextView tv2 = (TextView) layout.findViewById(R.id.group_app_rec_number);
        tv2.setText(gc.getNRec(app.getAppid(), group.getGroupID()).toString());
        
        return true;
    }

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	
	// display app activity view
	private void displayAppActivity(String app_name, String app_desc, String appid){
		 setContentView(R.layout.view_app);
		 this.appName = app_name;
		 this.appId = appid;
		 this.appDesc = app_desc;
		 
		 // init variables
		 TextView appNameText = (TextView) findViewById(R.id.app_app_name);
	        TextView appDescText = (TextView) findViewById(R.id.app_app_description);
	        recBtn = (Button) findViewById(R.id.app_recommend_btn);
	        recBtn.setVisibility(View.GONE);
 
	        this.appName = app_name;
//	        if(extras !=null)
//	        {
//	        	appName = extras.getString("app_name");
	        	appNameText.setText(appName);
	        	
//	        	appDesc = extras.getString("app_desc");
	        	appDescText.setText(appDesc);
	        	
//	        }
//	        	else{
//	        	appNameText.setText("N/A");
//	        	appDescText.setText("N/A");
//	        }
	        
	        // only display "Recommend" button when the app has been installed
	        // check if app exists in installed apps list
	        List<com.appkudos.model.App> installedApps = uc.getAppsForUser(user.getUsername());
	        com.appkudos.model.App app;
	        boolean installed = true;
	        for(int i=0; i<installedApps.size();i++) {
	        	app = (com.appkudos.model.App) installedApps.get(i);
	        	// if app in list does not have same id as app clicked, don't display "Recommend" button
	        	if (app.getAppid() == appid) {
	        		installed = false;
	        		//Toast.makeText(getApplicationContext(), app.getAppid() + " " + extras.getString("app_id") ,Toast.LENGTH_SHORT).show();
	        	  	  
	        	}
	        }
	        
	        
//	        recBtn.setOnClickListener(new OnClickListener() {
//	            @Override
//	            public void onClick(View v) {     
//	            	// hook button to Write Review screen
//	            	Intent intent = new Intent(PARENTACTIVITY, WriteReviewActivity.class);
//	        	    intent = uc.passCurrentUser(intent, user);
//	                intent.putExtra("app_name", appName);
//	        	    startActivity(intent);
//	            	displayWriteReviewActivity(appName, appDesc, appId);
//	            }
//	          }); 
//	       
//	        // hide "Recommend" button
//	        if (installed == false) {
//	        	recBtn.setVisibility(View.GONE);
//	        } 
	}
	
	
	   // display write review activity
		private void displayWriteReviewActivity(String app_name, String app_desc, String app_id){
			 setContentView(R.layout.view_write_review);
			 
			 appName = app_name;
			 appDesc = app_desc;
			 appId = app_id;
			 
			   recToFriendSpinner = (Spinner) findViewById(R.id.wr_rec_to_friend_spinner);
		       recToGroupSpinner = (Spinner) findViewById(R.id.wr_rec_to_group_spinner);
		    	
		    	appText = (TextView) findViewById(R.id.app_text);
		    	
		    	// fill app name based on previous screen
//		    	if (extras!= null) {
		    		appText.setText(app_name);
//		    	}
		    	
		    	appText.setOnClickListener(new OnClickListener() {
		            @Override
		            public void onClick(View v) {     
		            	// hook button to Write Review screen
			        	   App item = new App(appId, appName, appDesc);
//			        	   
			            	Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
			                  intent = uc.passCurrentUser(intent, user);
			                  if(friend!=null){
			                	  intent = uc.passFriend(intent, friend);
			                  }
			                  intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
			                  intent.putExtra("display_opt", "view_app");
			                  intent = uc.passApp(intent, item);
			          		  startActivity(intent);
		            	
//		            	 displayAppActivity(appName, appDesc, appId);
		        	    
		            }
		          });  
		    	commentEditText = (EditText) findViewById(R.id.wr_comment_edittext);
		    	
		    	postReviewBtn = (Button) findViewById(R.id.wr_post_review_btn);	    	
		    	postReviewBtn.setOnClickListener(new OnClickListener() {
		            @Override
		            public void onClick(View v) {     
		            	int friend = recToFriendSpinner.getSelectedItemPosition();
			    		int group = recToGroupSpinner.getSelectedItemPosition();
			    		String comment = commentEditText.getText().toString();
			    		
			    		if (friend == 0 && group == 0){
			    			Toast.makeText(getApplicationContext(), "No friend/group selected",Toast.LENGTH_SHORT).show();
			    		}else if(comment.compareTo("")==0){
			    			Toast.makeText(getApplicationContext(), "Please enter comment",Toast.LENGTH_SHORT).show();
			    		}else{
			    			if (friend != 0){
			    				String friendString = recToFriendSpinner.getItemAtPosition(friend).toString();
			    				rc.addRecommendation(user.getUsername(), comment, appId, 
			        					friendString, false);
			    			}
			    			
			    			if (group != 0){
//			    				String groupString = recToGroupSpinner.getItemAtPosition(group).toString();
			    				String groupString = user_groups.get(group-1).getGroupID();
//			    				Toast.makeText(getApplicationContext(), "gid: "+groupString+",gname: "+,Toast.LENGTH_LONG).show();
			    				rc.addRecommendation(user.getUsername(), comment, appId, 
			        					groupString, true);
			    			}
			    			
			    			Toast.makeText(getApplicationContext(), "Sent!",Toast.LENGTH_SHORT).show();
			    			Intent intent = new Intent(PARENTACTIVITY, com.appkudos.view.AppKudos.class);
				        	intent = uc.passCurrentUser(intent, user);
//				        	intent.putExtra("app_name", appName);
				        	startActivity(intent);
			    		}
			    		
			    		//showDialog( 0 );
			        
		            }
		          }); 
		        populateRecommendTo();
		}
		
	   // populate the fields in write review activity	
	   public void populateRecommendTo() {
		    	// TODO (The name of the app and username has to be set before!!!)
		    	//appText.setText("10");
		    	
		    	//Friends
		    	//UserController uc = new UserController();
		    	List<User> user_friends = uc.getFriendsOfUser(user.getUsername());
//	    		Toast.makeText(getApplicationContext(), "spinner_num_friends:" + user_friends,Toast.LENGTH_SHORT).show();
		    	ArrayAdapter <CharSequence> adapter =
		    		  new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item);
		    	adapter.add("Choose a friend");
		    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    	for (int i=0; i<user_friends.size(); i++){
		    		adapter.add(user_friends.get(i).getUsername());
		    	}
		    	
		    	recToFriendSpinner.setAdapter(adapter); 		 
		    	
		    	//Groups
		    	user_groups = uc.getGroupsOfUser(user.getUsername());
		    	
		    	ArrayAdapter <CharSequence> adapter2 =
		    		  new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item);
		    	adapter2.add("Choose a Group");
		    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    	for (int i=0; i<user_groups.size(); i++){
		    		adapter2.add(user_groups.get(i).getGroupName());
		    	}
		    	
		    	// if group has been selected for an app to be recommended to it, fill in group name in spinner
		    	if (group != null) {
		    		String groupName = group.getGroupName();
		    		Toast.makeText(getApplicationContext(), "Group " + groupName + " was selected",Toast.LENGTH_SHORT).show();
		    		// search for this group name in the spinner
		    		int spinnerPosition = adapter.getPosition(groupName);
		    		Toast.makeText(getApplicationContext(), "Group " + spinnerPosition + " was selected",Toast.LENGTH_SHORT).show();
		    		// set the spinner to display this group name
		    		recToGroupSpinner.setAdapter(adapter2);
		    		recToGroupSpinner.setSelection(spinnerPosition);
		    	}
		    	else {
		    		recToGroupSpinner.setAdapter(adapter2);
		    	}
		    }  
	   
	   private void displaySelectApp(){
	   	// set content view to apps_view xml
	       setContentView(R.layout.view_title_list);  
	       
	       // set the title of the page 
	       title_tv=(TextView)findViewById(R.id.tl_title);
	       title_tv.setText("Select an app to recommend:");
	     
	       // get list view from layout
	       lv=(ListView)findViewById(R.id.tl_list);
	       
		    // initialize the list
	       initInstalledApps();
			
			// when item is clicked go to app page
		    lv.setOnItemClickListener(new OnItemClickListener() {
		           public void onItemClick(AdapterView<?> parent, View view,
		               int position, long id) {
		        	   
		        	   // When clicked, show a toast with the TextView text
		        	   App item = (App) list.get(position);
		        	   
//		        	   displayWriteReviewActivity(item.getAppName(), item.getAppDesc(), item.getAppid());
		        	   Intent intent = new Intent(PARENTACTIVITY, AppKudos.class);
		        	   intent = uc.passCurrentUser(intent, user);
		        	   intent = uc.passFriend(intent, friend);
		        	   intent.putExtra("tab", PARENTACTIVITY.getString(R.string.tab_user_app));
		               intent.putExtra("display_opt", "create_rec");
		        	   intent = uc.passApp(intent, item);
		          	   startActivity(intent);
		             
		           }
		    });
	   }
	   
	   /**
	    * populate the list in select app screen with installed apps
	    * @param pm - package manager
	    * @param i - iterator
	    */
	    private void initInstalledApps(){
	   	Map<String, App> itemData;
	   	List<Map<String, App>> listData = new ArrayList<Map<String, App>>();
	   	
	   	list = (ArrayList) uc.getAppsForUser(user.getUsername());
	   	
	   	// put the apps into a hashmap (used for input by simple adapter)
	   	for(int j=0; j<list.size();j++){
	   		itemData = new HashMap<String, App>(1);
	   		app = (App) list.get(j);
	   		itemData.put("select_app_text", app);
	   		listData.add(itemData);
	   	}    

	   	// bind simple adapter to the list view
	       SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.list_select_app,
	               new String[] {
	                   "select_app_text"
	               }, new int[] {
	                   R.id.select_app_text
	               });
	       
	       // bind viewBinder to adapter and set adapter to listview
	       simpleAdapter.setViewBinder(this);
	       lv.setAdapter(simpleAdapter);
	   }
}